/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.anwarsumawang.salapi;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author Anwar
 */
class ExpenseList {
    String jdbcConnectionString;
    ArrayList<Expense> expenseList;
    boolean staleList = true;
    Connection conn;

    public ArrayList<Expense> getExpenseList() {
        refreshExpenseList();
        return (ArrayList<Expense>) expenseList.clone();
    }

    public void addExpense(Expense expense) {
        try {
            if (conn == null) {
                conn = Connector.getConnection();
            }
            PreparedStatement stmt = conn.prepareStatement(
                    "INSERT INTO expenses (expenseName, expenseAmount, expenseCategory) VALUES (?, ?, ?)");
            stmt.setString(1, expense.getExpenseName());
            stmt.setBigDecimal(2, expense.getExpenseAmount());
            stmt.setString(3, expense.getExpenseCategory());
            stmt.executeUpdate();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void refreshExpenseList() {
        try {
            if (conn == null) {
                conn = Connector.getConnection();
            }
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM expenses");

            expenseList = new ArrayList<Expense>();
            while (rs.next()) {
                expenseList.add(new Expense(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));
            }

        } catch (Exception ex) {
            
        }
        staleList = false;
    }
    
}